package com.qys.livesMall.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.shop.mapper.H2DataPackageMapper;
import com.qys.livesMall.shop.mapper.ShopDataDetailMapper;
import com.qys.livesMall.shop.mapper.SysPacketEffectMapper;
import com.qys.livesMall.shop.modal.dto.DataDealDTO;
import com.qys.livesMall.shop.modal.dto.QueryShopDataDetailDTO;
import com.qys.livesMall.shop.modal.entity.H2DataPackage;
import com.qys.livesMall.shop.modal.entity.ShopDataDetail;
import com.qys.livesMall.shop.modal.entity.SysPacketEffect;
import com.qys.livesMall.shop.modal.vo.ShopDataDetailVO;
import com.qys.livesMall.shop.service.ShopDataDetailService;
import jakarta.annotation.Resource;
import jdk.dynalink.Operation;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 店铺流量明细表
 * (ShopDataDetail)表服务实现类
 *
 * @author makejava
 * @since 2023-08-26 11:29:32
 */
@Service("shopDataDetailService")
public class ShopDataDetailServiceImpl extends ServiceImpl<ShopDataDetailMapper, ShopDataDetail> implements ShopDataDetailService {

    @Resource
    private H2DataPackageMapper dataPackageMapper;
    @Resource
    private SysPacketEffectMapper packetEffectMapper;

    /**
     * 分页查询
     *
     * @param dto 查询实体
     * @return
     */
    @Override
    public IPage<ShopDataDetailVO> selectAll(QueryShopDataDetailDTO dto) {
        return baseMapper.selectAllPage(new Page<>(dto.getPageNum(), dto.getPageSize()), dto);
    }

    @Override
    public void generateTransaction(DataDealDTO dto) {

        //本次交易量
        int volume;
        if("1".equals(dto.getTransactionType())){
            H2DataPackage dataPackage = dataPackageMapper.selectById(dto.getPacketId());
            if(dataPackage == null){
                throw new QysException("packetId error");
            }
            volume = dataPackage.getPackageContent() + Optional.ofNullable(dataPackage.getGiftData()).orElse(0);
        } else if("2".equals(dto.getTransactionType())) {
            SysPacketEffect packetEffect = packetEffectMapper.selectById(dto.getPacketId());
            if(packetEffect == null){
                throw new QysException("packetId error");
            }
            volume = Integer.parseInt(packetEffect.getConsume());
        } else {
            throw new QysException("transactionType error");
        }

        //保存数据
        ShopDataDetail dataDetail = new ShopDataDetail();
        dataDetail.setShopId(dto.getShopId());
        dataDetail.setTransactionType(dto.getTransactionType());
        dataDetail.setPacketId(dto.getPacketId());
        dataDetail.setVolume(volume);
        dataDetail.setCreateTime(LocalDateTime.now());
        this.save(dataDetail);
    }
}

